//
#include "data_source.h"
#include <iostream>
#include <thread>

DataSource::DataSource(const std::string& sourceTopicHost, const std::string& sourceTopic) : sourceTopicHost(sourceTopicHost), sourceTopic(sourceTopic) {
    std::cout << "DataSource ZMQ pub" << std::endl;
    // zmq::context_t ctx;
    pub = zmq::socket_t(ctx, zmq::socket_type::pub);
    pub.bind(sourceTopicHost.c_str());
    std::cout << "DataSource bind to " << sourceTopicHost << "..." << std::endl;
}

DataSource::~DataSource() {
    pub.close();
}

std::vector<uint8_t> DataSource::generateSignal() {
    // static std::mt19937 gen(std::random_device{}());
    std::vector<uint8_t> signal(4096);
    signal[0] = 67;
    signal[1] = 69;
    // std::generate(signal.begin(), signal.end(), [&]() { return gen() % 256});
    return signal;
}

void DataSource::mainLoop() {
    while (true) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout << "DataSource分发数据..." << std::endl;
        std::vector<uint8_t> signal = generateSignal();
        zmq::message_t topic(sourceTopic);
        zmq::message_t data(signal.data(), signal.size());
        if (!pub.send(topic, zmq::send_flags::sndmore) || !pub.send(data, zmq::send_flags::none)) {
            std::cerr << "Publisher: Faile to send frame" << std::endl;
            continue;
        }
    }
}